<template>
	<view >
		<cu-custom bgColor="bg-gradual-pink" :isBack="false">
<!-- 			<block slot="backText">返回</block> -->
			
			<block slot="right">
			  <uni-icons type="home" size="20" color="white" class="home-icon" @click="goHome"></uni-icons>
			</block>
			<block slot="content">外发单查询</block>
		</cu-custom>
	  <view class="container">
		<!-- 条件查询输入框 -->
		<view class="search-bar">
		  <!-- 输入框 -->
		  <view class="input-wrapper">
			  <input v-model="searchVal" placeholder="请输入查询数据"
			   @input="handleInput" 
			   :focus="focusStateProduct"
			   style="background-color: white;" 
			   autofocus
			   />
		  </view>
		  <button @click="search">查询</button>
		</view>
		<!-- 表格展示查询结果 -->
			<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据" @selection-change="selectionChange">
				<uni-tr>
					<uni-th width="20" align="center">序号</uni-th>
					<uni-th width="150" align="center">外发单号</uni-th>
					<uni-th align="center">厂商名称</uni-th>
					<uni-th width="150" align="center">下单日期	</uni-th>
					<uni-th width="150" align="center">需求日期</uni-th>
					<uni-th width="150" align="center">金额</uni-th>
					<uni-th width="150" align="center">税额</uni-th>
					<uni-th width="150" align="center">状态</uni-th>
					<!-- <uni-th width="204" align="center">设置</uni-th> -->
				</uni-tr>
				<uni-tr v-for="(item, index) in tableData" :key="index">
					<uni-td>{{ index + 1 }}</uni-td>
					<uni-td>{{ item.outsourceNo }}</uni-td>
					<uni-td align="center">{{ item.supplierId_dictText }}</uni-td>
					<uni-td>{{ item.createTime ? item.createTime.substring(0,10) : "" }}</uni-td>
					<uni-td>{{ item.orderDate }}</uni-td>
					<uni-td>{{ item.amount }}</uni-td>
					<uni-td>{{ item.taxAmount }}</uni-td>
					<uni-td>{{ item.status_dictText }}</uni-td>
				</uni-tr>
			</uni-table>
			<view class="uni-pagination-box"><uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total" @change="change" /></view>
	  </view>
	  <view class="example-body">
		<drawer :show="subOrderDrawerShow" @cancel="subOrderCancel" @ensure="subOrderEnsure" >
			<view style="margin-top: 240rpx;">
				<uni-table ref="itemTable" :loading="loading" border stripe type="selection" emptyText="暂无更多数据" @selection-change="selectionDrawChange">
					<uni-tr>
						<uni-th width="50" align="center">序号</uni-th>		
<!-- 						<uni-th width="150" align="center">工单号</uni-th>
						<uni-th width="150" align="center">客户</uni-th> -->
						
						<uni-th width="150" align="center">客户料号</uni-th>
						<uni-th width="120" align="center">图号</uni-th>
						<uni-th width="120" align="center">产品名称</uni-th>
						<uni-th width="150" align="center">版本</uni-th>
						<uni-th width="120" align="center">外发数量</uni-th>
						<uni-th width="120" align="center">收货数量</uni-th>
						<uni-th width="120" align="center">待收数量</uni-th>						
						<uni-th width="120" align="center">已收数量</uni-th>
						<uni-th width="120" align="center">退货数量</uni-th>
						<uni-th width="120" align="center">下单日期</uni-th>	
						<uni-th width="120" align="center">产品编码</uni-th>
							
					</uni-tr>
					<uni-tr v-for="(item1, index) in itemChilds" :key="index">
						<uni-td>{{ (index + 1) }}</uni-td>
<!-- 						<uni-td>{{ item1.workOrderNumber }}</uni-td>
						<uni-td>{{ item1.customerShortName }}</uni-td> -->
						
						<uni-td>		{{item1.custCode}}		</uni-td>
						  <uni-td>		{{item1.drawingNo}}		</uni-td>
						<uni-td>		{{item1.productName}}		</uni-td>
						<uni-td>		{{item1.productVer}}		</uni-td>
						<uni-td>		{{item1.qty}}		</uni-td>
						<uni-td align="center">
							<input :ref="'inputQty' + index " placeholder="请输入收货数量" name="input" @input="inputQty" @change="inputQtyChange($event,index,item1)" v-model="item1.inputQty"></input>
						</uni-td>
						<uni-td>		{{item1.balQty}}		</uni-td>
						
						<uni-td>		{{item1.qtyReceipt ? item1.qtyReceipt : 0}}		</uni-td>
						<uni-td>		{{item1.qtyReturn ? item1.qtyReturn : 0}}		</uni-td>
						<uni-td>		{{item1.orderDate ? item1.orderDate : '' }}		</uni-td>
						<uni-td>{{ item1.productCode }}			</uni-td>
					</uni-tr>
				</uni-table>
			  </view>
			</drawer>	
		</view>
  </view>
</template>

<script>
import { ACCESS_TOKEN,USER_NAME,USER_INFO,SASS_TENANT_ID,EMPLOYEE_INFO,SASS_DOMAIN_ID,SASS_DOMAIN_NAME} from "@/common/util/constants"
import configService from '@/common/service/config.service.js';
import { forEach } from "../../common/luch-request/utils";
	import api from '@/api/api.js'
import CustomDownSearch from '@/components/my-componets/custom-down-search.vue'
import tableData from '../workorder/table/tableData.js'
	
export default {
	components: {
		CustomDownSearch,
	},
  data() {
    return {
		subOrderDrawerShow:false,
      searchKeyword: '',
	  searchVal: '',
	  uuid : '2971b0f1-29a9-4a36-9f2d-cc7e01256b94', //'ebfd5729-7f9e-4109-a025-077c17a9edcc',
	  tenantId : '22', //'22',
	  supplierId : '1609000658982178818',
	  searchCustId: null,
	  outsourceNo:'',
		tableData: [],
		selectedRow : {},
		itemChilds : [],
		custList : [],
		custListText : [],
		// 每页数据量
		pageSize: 10,
		// 当前页
		pageCurrent: 1,
		// 数据总量
		total: 0,
		loading: false,
		customNumberConfig: {
			ruleField: 'dnNumber',
			ruleCode: 'out_dn_number', //pom_delivery_note_no
			ruleName: '采购收货单编码',
			ruleUrl: '/sys/fillRule/executeRuleByCode/',
		},		
	  url : {
		   custList : '/bas/basCustomer/list',
		   list: '/opm/opmOutsourceProcess/list',
		   queryById : '/opm/opmOutsourceProcess/queryOpmOutsourceProcessItemByMainId',
		   login: '/sys/shareLinkLogin',
		   checkSign: '/sys/checkUuid',
	  }
    };
  },
  onLoad(options) {
  	setTimeout(() => {
  	  console.log(options);
  	  if (options.uuid) {
  		this.uuid =options.uuid;
  	  } 
  	  if (options.supplierId) {
  		this.supplierId = options.supplierId;
  	  } 
  	  if (options.tenantId) {
  		this.tenantId = options.tenantId;
  	  }	
	  if (this.uuid) {
		  this.checkSign()
	  }
  	}, 800);	  
	  
  		this.selectedIndexs = []
  		// this.getData(1)
  },
  created(){
	  this.getCusts()
	  this.getCustomNumber()
  },
  methods: {
		getCustomNumber() {
			this.$http.put(
				this.customNumberConfig.ruleUrl + this.customNumberConfig.ruleCode, {
					params: {}
				}
			).then((res) => {
				debugger
				// 执行成功，获取返回的值，并赋到页面上
				if (res.data && res.data.result) {
					this.outsourceNo = res.data.result;
				}
			});
		},	  
	  inputQty(val) {

	  },
	  inputQtyChange(e,index,row) {
		if (e.detail.value > row.balQty) {
			// this.$refs['inputQty' + index].focus()
			this.$tip.error("第" + (index + 1) + "行数量超过了剩余收货数量！")
		}
	  },
	  checkSign() {
		  let that = this
		this.loading = true;
		let params = {uuid:this.uuid + this.tenantId}
		this.$http.get(this.url.checkSign, {
				params: params
		}).then((res) => {
			that.checkString = JSON.stringify(res)
			if (res.data.success) {
				const result = res.data.result
				uni.setStorageSync(SASS_TENANT_ID,result.tenantId);
				this.biz = 'temp/' + result.tenantId  
				this.login()
			} else {
				this.$tip.toast(res.data.message)
			}
		}).catch(err => {
					that.err = JSON.stringify(err)
					that.$tip.error(err.data.message)
				}).finally(() => {
			that.loading = false
		})
	  },
	  login(){
		  let that = this
			this.loading = true;
			this.$http.post(this.url.login, {
					uuid: this.uuid,
					supplierId: this.supplierId,
					tenantId: this.tenantId,
			}).then((res) => {
				console.log(res)
				that.loginRes = JSON.stringify(res)
						if (res.data.success) {					
							const result = res.data.result
							const userInfo = result.userInfo
							uni.setStorageSync(ACCESS_TOKEN,result.token);
							uni.setStorageSync(USER_INFO,userInfo);
							this.getData(1)
							// this.loadData()
						} else {
							this.$tip.toast(res.data.message)
						}
				}).catch(err => {
					that.err = JSON.stringify(err)
					that.$tip.error(err.data.message)
				}).finally(() => {
					that.loading = false
				})
	  },	  
	 handleTouchStart(event) {
		  // 获取触摸点的信息
		  const touch = event.touches[0];
		  const x = touch.clientX;
		  const y = touch.clientY;
		  console.log(`触摸开始，坐标为：(${x}, ${y})`);
		  this.$refs.selSupp.handelDropDown(x,y)
		},	  
	  getCusts() {
	  	console.log("beging find cust.")
	  	this.$http.get(
	  		this.url.custList, {
	  			params: {
	  				pageSize: 1000,
	  				status:1
	  			}
	  		}).then(res => {
	  		console.log("res::cust>", res)
	  		if (res.data.result.records) {
	  			let data = res.data.result.records
	  			this.custList = []
	  			data.forEach((item) => {
	  				let obj = {
	  					value: item.id,
	  					text: item.shortName
	  				}
	  				this.custList.push(obj)
					this.custListText.push(obj.text)
	  			})
	  		}
	  	})
	  },
	  handleDetail(id){
		  let that = this
		  let params = {
		  	'id' : id,
		  }
		  this.loading = true
		  this.$http.get(this.url.queryById, {
		  	params: params
		  }).then(res => {

		  	this.loading = false
		  	that.itemChilds = res.data.result.records || res.data.result;
			that.itemChilds.forEach((p,k)=>{
				let receiptQty = p.qtyReceipt ? p.qtyReceipt : 0
				let returnQty = p.qtyReturn ? p.qtyReturn : 0
				// p.balQty = p.qty - receiptQty
				p.inputQty = 0;
				this.$set(p, 'balQty', p.qty - receiptQty);
				
			})
		  	console.log(that.itemChilds)
			console.log(res.data.result)
			that.$nextTick(()=>{
				this.subOrderDrawerShow = true
			})
			
		  })
	  },
		subOrderCancel() {
			console.log('您点击了取消按钮')
			this.subOrderDrawerShow = false;
		},
		//确定
		subOrderEnsure(){
			let checkSaveFlag = false
			this.itemChilds.forEach((p,k) =>{
				if (p.inputQty > 0) {
					if (p.inputQty > p.balQty) {
						this.$tip.error("第" + (k + 1) + "行数量超过了剩余收货数量！")
						return
					}							
					checkSaveFlag = true								
				}
			})
			if (!checkSaveFlag) {
				this.$tip.error("没有保存的数据！")
				return
			}
			console.log('您点击了确定按钮')
			this.subOrderDrawerShow = false;
			this.onSubmit()
		},		
		onSubmit(status) {
			debugger
			let flag = false
			let param = Object.assign({},this.selectedRow) 			
			param.outsourceProcessId = param.id 
			param.id = null
			param.dnType = 1
			param.dnNumber = this.outsourceNo
			param.dnDate = new Date()
			param.status = "2"
			param.opmDeliveryNoteItemList = []
			this.itemChilds.forEach((p,k)=>{
				let obj = p 
				obj.qty = obj.inputQty
				obj.status = "2"
				obj.outsourceProcessId = param.outsourceProcessId
				obj.outsourceProcessItemId = obj.id
			    obj.id = null
				param.opmDeliveryNoteItemList.push(obj)
			})
			param.opmDeliveryNoteStatusList = []
			console.log(param)
			let messages = ''
			this.$tip.loading();
			this.$http.post('/opm/opmDeliveryNote/add-supp', param).then(res => {
				console.log(res)
				this.$tip.loaded();
				if (res.data.success) {
					this.$tip.toast('提交成功')
					this.getCustomNumber();
				} else {
					this.$tip.loaded();
					this.$tip.alert(res.data.message)
				}
			}).catch((e) => {
				this.$tip.loaded();
				this.$tip.error('提交失败')
			});
		},		  
	  setFocusProduct() {
		let that = this
		this.$nextTick(()=>{
			setTimeout(() => {
						that.focusStateProduct = true
				},1000)
		})
	  
	  },
	  handleInput() {
		  
	  },
	  selectedItems() {
	  	  			return this.selectedIndexs.map(i => this.tableData[i])
	  	  		},
		// 多选
		selectionDrawChange(e) {
			
		},
		selectionChange(e) {
			console.log(e.detail.index)
			this.selectedIndexs = e.detail.index
			if (this.selectedIndexs.length == 1) {
				let rows = this.selectedItems()
				this.selectedRow = rows[0]
				this.handleDetail(rows[0].id)
			}
		},
		goHome() {
		  uni.navigateTo({
		    url: '/pages/login/login'
		  });
		},
		//批量删除
		delTable() {
			console.log(this.selectedItems())
		},
		// 分页触发
		change(e) {
			this.$refs.table.clearSelection()
			this.selectedIndexs.length = 0
			this.getData(e.current)
		},
		clearSearchKeyword() {
			debugger
		  this.searchVal = ''
		},
		// 搜索
		search() {
			this.getData(1, this.searchVal)
		},
        getData(pageCurrent, value = '') {
				this.pageCurrent = pageCurrent
				let that = this
				let params = {
					'queryName' : value,
					'pageNo': this.pageCurrent,
					'pageSize': this.pageSize,
					'column': 'createTime,updateTime',					
					'order': 'desc',
				}
				let superArr = []
				superArr.push({"rule":"eq","type":"string","val":'3',"field":"op.status"})
				superArr.push({"rule":"eq","type":"string","val":this.supplierId,"field":"op.supplierId"})
				params.superQueryMatchType = 'and'
				params.superQueryParams = encodeURIComponent(JSON.stringify(superArr))
				
				this.loading = true
				this.$http.get(this.url.list, {
					params: params
				}).then(res => {
					this.loading = false
					this.tableData = res.data.result.records || res.data.result;
					console.log(this.tableData)
					this.setFocusProduct()
					if (res.data.result.total) {
						this.total = res.data.result.total						
					} else {
						this.total = 0
					}
				})
			},		
		// 获取数据
		getData1(pageCurrent, value = '') {
			this.loading = true
			this.pageCurrent = pageCurrent
			this.request({
				pageSize: this.pageSize,
				pageCurrent: pageCurrent,
				value: value,
				success: res => {
					// console.log('data', res);
					this.tableData = res.data
					this.total = res.total
					this.loading = false
				}
			})
		},
	  // 伪request请求
		request(options) {
			const { pageSize, pageCurrent, success, value } = options
			let total = tableData.length
			let data = tableData.filter((item, index) => {
				const idx = index - (pageCurrent - 1) * pageSize
				return idx < pageSize && idx >= 0
			})
			if (value) {
				data = []
				tableData.forEach(item => {
					if (item.name.indexOf(value) !== -1) {
						data.push(item)
					}
				})
				total = data.length
			}
  
			setTimeout(() => {
				typeof success === 'function' &&
					success({
						data: data,
						total: total
					})
			}, 500)
		},
	  
  }
};
</script>

<style scoped>
.input-wrapper {
  position: relative;
  flex: 1;
}
  .home-icon {
    // position: absolute;
    // top: 20rpx;
    margin-left: 10px;
  }
.input-wrapper input {
  width: 100%;
  height: 40px;
  padding: 0 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
   box-sizing: border-box; /* 确保内边距和边框不会增加元素的宽度 */
}
.clear-button {
  position: absolute;
  top: 50%;
  right: 20px; /* 调整按钮的位置，避免被输入框的边框遮挡 */
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #999;
  font-size: 16px;
  cursor: pointer;
  z-index: 1; /* 确保按钮在最上层，不会被其他元素遮挡 */
}	
.container {
  padding: 6px;
}
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.search-bar input {
  flex: 1;
  height: 40px;
  padding: 0 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
}
.search-bar button {
  height: 40px;
  padding: 0 20px;
  background-color: #007aff;
  color: #fff;
  border: none;
  border-radius: 5px;
  align-items: center;
  line-height: 40px;
}
uni-table {
  margin-bottom: 20px;
}
uni-pagination {
  display: flex;
  justify-content: center;
}
</style>